import Wx from 'weixin-js-sdk';
import Store from '@store/index';
import { user_wxShareInfo } from '@api/user';
import { Toast } from 'vant';
export default {
  showCopyMenu() {
    let url = Store.state.shareUrl ? Store.state.shareUrl : window.location.href;
    user_wxShareInfo({ url }).then(res => {
      if (res.code === 200) {
        let { appId, timestamp, nonceStr, signature } = res.data;
        Wx.config({
          debug: false, // 开启调试模式
          appId, // 必填，公众号的唯一标识
          timestamp, // 必填，生成签名的时间戳
          nonceStr, // 必填，生成签名的随机串
          signature, // 必填，签名，见附录1
          jsApiList: ['showMenuItems']
        });
        Wx.ready(() => {
          Wx.showMenuItems({
            menuList: ['menuItem:copyUrl', 'menuItem:openWithSafari', 'menuItem:openWithQQBrowser']
          });
        });
      } else {
        Toast(res.msg);
      }
    });
  },
  wxShare(shareCont) {
    if (!shareCont) {
      return Toast('分享参数不能为空！');
    }
    // 如果store储存了shareUrl代表是ios需要读取初始的url;
    let url = Store.state.shareUrl ? Store.state.shareUrl : window.location.href;
    user_wxShareInfo({ url }).then(res => {
      if (res.code === 200) {
        let { appId, timestamp, nonceStr, signature } = res.data;
        Wx.config({
          debug: false, // 开启调试模式
          appId, // 必填，公众号的唯一标识
          timestamp, // 必填，生成签名的时间戳
          nonceStr, // 必填，生成签名的随机串
          signature, // 必填，签名，见附录1
          jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData', 'showMenuItems']
        });
        Wx.ready(res => {
          Wx.showMenuItems({
            menuList: ['menuItem:copyUrl', 'menuItem:share:appMessage', 'menuItem:share:timeline', 'menuItem:share:qq', 'menuItem:favorite', 'menuItem:share:QZone', 'menuItem:profile'],
            success: function(res) {},
            fail: function(res) {}
          });
          let shareContent = Object.assign(shareCont, {
            success() {
              // Toast('分享成功');
            },
            cancel() {
              // Toast('分享失败');
            }
          });
          // 自定义“分享给朋友”及“分享到QQ”按钮的分享内容
          Wx.updateAppMessageShareData(shareContent);
          // 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容
          Wx.updateTimelineShareData(shareContent);
        });
      } else {
        Toast(res.msg);
      }
    });
  },
  // 隐藏按钮不允许分享
  hideMenu() {
    if (typeof window.WeixinJSBridge == 'undefined') {
      if (document.addEventListener) {
        document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false);
      } else if (document.attachEvent) {
        document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady);
        document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady);
      }
    } else {
      this.onBridgeReady();
    }
  },
  onBridgeReady() {
    window.WeixinJSBridge.call('hideOptionMenu');
  },
  closeCurrentWindo() {
    Wx.closeWindow();
  }
};
